<?php

namespace service\excel\order;

use api\storage\common\Constant;
use app\storage\common\AppConstant;
use app\storage\common\Template;
use app\storage\model\PurchaseModel;
use app\storage\model\StorageModel;
use service\excel\AbstractExcel;
use service\file\CommonFile;
use think\Config;
use think\Db;

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/3/2
 * Time: 15:44
 */
class ReelBom extends AbstractExcel
{

    public function __construct()
    {
        parent::__construct();
        $this->config = Config::get('reel_bom');
    }

    public function getData()
    {
        $reader = $this->phpReader->load($this->path);
        $sheet = $reader->getSheet(0);//获取第一个工作区
        $this->tableData['orderId'] = trim($sheet->getCgell($this->config['orderId'])->getValue());
        $this->tableData['orderId'] = empty($this->tableData['orderId']) ? create_unique_id('BOM') : $this->tableData['orderId'];
        $this->tableData['storageName'] = trim($sheet->etCell($this->config['storageName'])->getValue());
        $this->tableData['remark'] = trim($sheet->getCell($this->config['remark'])->getValue());
        $dataBegin = $this->config['begin'];
        for ($i = $dataBegin; $i < $sheet->getHighestRow(); $i++) {
            $reelId = strtoupper(trim($sheet->getCell($this->config['reelId'] . $i)->getValue()));
            $count = trim($sheet->getCell($this->config['count'] . $i)->getValue());
            if (empty($reelId)) {
                break;
            }
            $this->tableData['bom'][] = [
                'reel_Id' => $reelId,
                'count' => $count,
            ];
        }
    }

    public function checkData()
    {
        $storageModel = new StorageModel();
        $storageInfo = $storageModel->getStorageInfoByName($this->storageName);
        if (empty($storageInfo)) {
            return ret_template(false, "仓库({$this->storageName}不存在)");
        }
        $reel = array_column($this->tableData['bom'], 'reel_id');
        if (empty($reel)) {
            return ret_template(false, '请导入出库单条码');
        }
        $purchaseModel = new PurchaseModel();
        $exists = $purchaseModel->whereIn('reel_id', $reel)->order('reel_id asc')->select();
        $reelsDb = count($exists) ? $exists->toArray() : [];
        $error = array_diff($reel, array_column($reelsDb, 'reel_id'));
        if ($error) {
            $index = [];
            //记录不在库reelId并把索引返回提示,+3是为了转换为excel上的具体行，第3行开始填写ReelId
            foreach ($error as $item) {
                $index[] = array_search($item, $reel) + 3;
            }
            $indexString = implode('、', $index);
            return ret_template(false, "{$indexString}行reelId不在系统中");
        } else {
            $bomUuid = create_uuid();
            $bom = Template::bomTemplate($bomUuid, $this->tableData['orderId'], '', $this->tableData['storageName'], $storageInfo['supplier_uuid'], 5, AppConstant::BOM_B,0, '', '', '按条码出库');
            $bomDetail = [];
            $reels = array_column($reelsDb, 'reel_id');
            //如果没有填写出库数量或大于在库数量则按整件都出
            foreach ($reel as $k => &$item) {
                $index = array_search($item, $reels);
                if ($item['count'] > $reelsDb[$index]['count'] || intval($item['count']) < 0 || empty($item['count'])) {
                    $item['count'] = $reelsDb[$index]['count'];;
                    //  $this->tableData['bom'][$k]['count'] = $reelsDb[$index]['count'];
                }
                $temp = $item['sub_materiel_id'];
                $count = $item['count'] + $bomDetail[$temp]['count'];
                $bomDetail[$temp] = Template::bomDetailTemplate($bomUuid,$temp,$count);
            }

            $this->tableData = $this->tableDataTemplate($bom, $bomDetail, $reelsDb);
        }
        return ret_template(true, "获取成功", $this->tableData);
    }

    public function insertToDb()
    {
        $bom = $this->tableData['bom'];
        $detail = $this->tableData['detail'];
        $bomDetail = array_values($detail);
        Db::startTrans();
        $tranBom = Db::table('iwh_bom')->insert($bom);
        $tranDet = Db::table('iwh_bom_detail')->insertAll($bomDetail);
        if ($tranBom && $tranDet) {
            Db::commit();
            return ret_template(true, '成功生成单据');
        } else {
            Db::rollback();
            return ret_template(false, '生成单据失败');
        }
    }

    public function createReturnReelsFile()
    {
        $reel = $this->tableData['reel'];
        $reels = [];
        foreach ($reel as $item) {
            $reels[] = Template::returnReelsTemplate($item['reel_id'],$item['seat_code'],$item['sub_materiel_id'],$item['count']);
        }
        $filePath = Constant::RECORD_RETURN_REELS . $this->tableData['orderId'] . Constant::RECORD_FILE_SUFFIX;
        $file = new CommonFile($this->storageUuid, $filePath);
        $file->write($reels);
    }

    protected function tableDataTemplate($bom, $bomDetail, $reelsDb = [])
    {
        return [
            'bom' => $bom,
            'detail' => $bomDetail,
            'reel' => $reelsDb
        ];
    }
}